<?php

namespace App\Http\Controllers\Test;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Pusher\Pusher;

class ChatController extends Controller
{
    //
    var $pusher;
    var $user;
    var $chatChannel;

    const DEFAULT_CHAT_CHANNEL='chat';

    public function __construct()
    {
        $app_key=getenv('PUSHER_KEY');
        $app_secret=getenv('PUSHER_SECRET');
        $app_id=getenv('PUSHER_APP_ID');
        $app_cluster=getenv('PUSHER_APP_CLUSTER');

        $this->pusher=new Pusher($app_key, $app_secret, $app_id, array( 'cluster' => $app_cluster));
        $this->username="swaggerz";
        $this->chatChannel=self::DEFAULT_CHAT_CHANNEL;
    }

    public function getIndex()
    {
        if(!$this->username)
        {
            return redirect('login');//用户没有认证过则跳转github页面认证下
        }

        return view('test.chat', ['chatChannel' => $this->chatChannel]);
    }

    public function postMessage(Request $request)
    {
        $message=[
            'text' => e($request->input('chat_text')),
            'username' => $this->username,
            'timestamp' => (time()*1000)
        ];

        $this->pusher->trigger($this->chatChannel, 'new-message', $message);
    }

}
